import axios from "axios";
import { getToken, removeToken } from "./cookie";
import router from "@/router";

// 不同的功能，通过axios请求的是不同接口地址
const service = axios.create({
    baseURL: "/dev-api",
    timeout: 10000,
    withCredentials: true  // 允许跨域携带cookie
})

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        if (getToken()) {
            config.headers["Authorization"] = "Bearer " + getToken();
        }
        return config;
    },
    (error) => {
        Promise.reject(error);
    }
);


// 响应拦截器
service.interceptors.response.use(
    (res) => {
        // 未设置状态码则默认成功状态
        const code = res.data.code || 1000;
        const msg = res.data.msg;
        if (code === 3001) {
            ElMessage({ message: msg, type: "warning" });
            removeToken();
            router.replace("/forum/login");
            return Promise.reject(new Error(msg));
        } else if (code !== 1000) {
            ElMessage({ message: msg, type: "error" });
            // ElNotification.error({ title: msg });
            return Promise.reject(new Error(msg));
        } else {
            return Promise.resolve(res.data);
        }
    },
    (error) => {
        console.log("err" + error);
        let { message } = error;
        if (message == "Network Error") {
            message = "后端接口连接异常";
        } else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        }
        return Promise.reject(error);
    }
);

export default service

//